﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Photon.SocketServer;

namespace MyApplication
{
    public class PeerManager : IDisposable
    {
        private static PeerManager mSingle = new PeerManager();
        private PeerManager()
        { }

        public static PeerManager Single
        {
            get { return mSingle; }
        }

        private Dictionary<MyPeer, string> mList = new Dictionary<MyPeer, string>();

        public void AddPeer(MyPeer peer, string userName)
        {
            TrimPeerList();
            mList.Add(peer, userName);
        }

        public void DeletePeer(MyPeer peer)
        {
            mList.Remove(peer);
        }

        public void ClearAll()
        {
            mList.Clear();
        }

        public MyPeer[] GetPeers()
        {
            TrimPeerList();

            return mList.Keys.ToArray();
        }

        public int GetPeerCount()
        {
            TrimPeerList();

            return mList.Count;
        }

        private void TrimPeerList()
        {
            List<MyPeer> deleList = new List<MyPeer>();
            foreach (var item in mList)
            {
                if (item.Key.Disposed)
                {
                    item.Key.SaveToDB();
                    deleList.Add(item.Key);
                }
            }

            foreach (var item in deleList)
            {
                mList.Remove(item);
            }
        }

        public string GetUserName(MyPeer peer)
        {
            string name = string.Empty;
            if(mList.TryGetValue(peer, out name))
            {
                return name;
            }

            return null;
        }

        public void Dispose()
        {
            this.ClearAll();
        }
    }
}
